#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define N 256
#define UDP_PORT 8888

int main(int argc, char const *argv[])
{
    int udp_fd;

    // 创建UDP套接字
    if ((udp_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        perror("UDP socket创建失败");
        return -1;
    }

    // UDP地址绑定
    struct sockaddr_in udp_addr = {
        .sin_family = AF_INET,
        .sin_port = htons(UDP_PORT),
        .sin_addr.s_addr = INADDR_ANY};

    if (bind(udp_fd, (struct sockaddr *)&udp_addr, sizeof(udp_addr)) < 0)
    {
        perror("UDP绑定失败");
        close(udp_fd);
        return -1;
    }

    printf("设备等待搜索请求中...\n");

    while (1)
    {
        char buf[N] = {0};
        struct sockaddr_in cliaddr;
        socklen_t addrlen = sizeof(cliaddr);

        // 接收UDP请求
        ssize_t len = recvfrom(udp_fd, buf, N, 0,
                               (struct sockaddr *)&cliaddr, &addrlen);
        if (len < 0)
        {
            perror("UDP接收失败");
            continue;
        }

        printf("收到UDP请求: %s，来自 %s:%d\n",
               buf,
               inet_ntoa(cliaddr.sin_addr),
               ntohs(cliaddr.sin_port));

        // 处理搜索请求
        if (strcmp(buf, "SEARCH_DEVICE") == 0)
        {
            // 准备设备信息JSON
            char device_info[N];
            snprintf(device_info, N,
                     "设备名称:摄像头,版本:1.0,端口:%d",UDP_PORT);
            // 发送响应
            if (sendto(udp_fd, device_info, strlen(device_info), 0,
                       (struct sockaddr *)&cliaddr, addrlen) < 0)
            {
                perror("UDP响应发送失败");
            }
            else
            {
                printf("已发送设备信息: %s\n", device_info);
            }
        }
    }

    close(udp_fd);
    return 0;
}
